package tech.yunland.shop.web;

import com.moyuer.bsf.common.PinYinUtil;
import com.moyuer.bsf.common.Validator;
import com.moyuer.bsf.common.codec.SecureCoder;
import com.moyuer.bsf.common.web.AuthNotRequired;
import com.moyuer.bsf.domain.model.Organ;
import com.moyuer.bsf.domain.model.User;
import com.moyuer.bsf.domain.model.UserOpenId;
import com.moyuer.bsf.domain.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.service.RegisterService;
import tech.yunland.shop.domain.service.SNService;

import java.security.NoSuchAlgorithmException;

/**
 * 用户注册
 *
 * @author: 袁首京<yuanshoujing@gmail.com>
 * 16/5/7
 */
@RestController
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private SNService snService;

    /**
     * 注册
     *
     * @param account  账户
     * @param password 密码
     * @param kindcode 类型代码 10 店员 20 会员
     * @param name     名称
     */
    @AuthNotRequired
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void register(@RequestParam String account,
                         @RequestParam String password,
                         @RequestParam String kindcode,
                         @RequestParam(required = false) String name) {

        account = StringUtils.trimToNull(account);
        password = StringUtils.trimToNull(password);

        kindcode = StringUtils.trimToNull(kindcode);
        if (!"10".equals(kindcode)) {
            kindcode = "20"; // 默认为会员注册
        }

        name = StringUtils.trimToNull(name);
        if (name == null) {
            name = account;
        }

        // 判断账户是否被占用
        boolean exist = userService.exist(account, null);
        if (exist) {
            throw new RuntimeException("账户已经被占用");
        }

        User user = new User();
        user.setAccount(account);
        user.setName(name);
        user.setSpell(PinYinUtil.getFirstSpell(name));
        user.setKindCode(kindcode);

//        // 如果账户为电话号码, 则设置电话号码
//        if (Validator.checkMobile(account) || Validator.checkTelephone(account)) {
//            user.setTel(account);
//        }

        if (Validator.checkEmail(account)) {
            user.setEmail(account);
        }

        String securePassword = null;
        try {
            securePassword = SecureCoder.sha1(password);
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("密码加密失败");
        }

        user.setPassword(securePassword);

        registerService.addForRegister(user);
    }

    /**
     * 第三方账户注册
     *
     * @param platform
     * @param openid
     * @param kindcode 类型代码 10 店员 20 会员
     * @return
     */
    @AuthNotRequired
    @RequestMapping(value = "/by/{platform}/{openid}", method = RequestMethod.POST)
    public void login(@PathVariable String platform,
                      @PathVariable String openid,
                      @RequestParam String kindcode,
                      @RequestParam(required = false) String userId) {
        platform = StringUtils.trimToNull(platform);
        openid = StringUtils.trimToNull(openid);

        kindcode = StringUtils.trimToNull(kindcode);
        if (!"10".equals(kindcode)) {
            kindcode = "20"; // 默认为会员注册
        }

        if (platform == null) {
            throw new RuntimeException("platform 不能为空");
        }
        else if (openid == null) {
            throw new RuntimeException("openid 不能为空");
        }

        User userInDb = userService.get(platform, openid);
        if (userInDb != null) {
            if (userInDb.getState() < 1) {
                throw new RuntimeException("账户未激活或已删除");
            }

            return;
        }

        userId = StringUtils.trimToNull(userId);
        // 生成用户
        User user = null;
        if (userId != null) {
            user = userService.get(userId);
        }

        boolean userExists = false;
        if (user == null) {
            user = new User();
            String sn = snService.gen("account", Organ.ROOT_ID);
            user.setAccount(sn);
            user.setName(sn);
            user.setSpell(PinYinUtil.getFirstSpell(sn));
            user.setKindCode(kindcode);

            String securePassword = null;
            try {
                securePassword = SecureCoder.sha1(RandomStringUtils.randomAlphanumeric(8)); // 随机密码
            }
            catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("密码加密失败");
            }

            user.setPassword(securePassword);
        }
        else {
            userExists = true;
        }

        // 记录openid
        UserOpenId userOpenId = new UserOpenId();
        userOpenId.setOwner(user);
        userOpenId.setPlatform(platform);
        userOpenId.setOpenId(openid);

        if (userExists) {
            userService.bindOpenId(userOpenId);
        }
        else {
            registerService.addForRegister(userOpenId);
        }
    }


}
